package com.chis.netty.mqtt.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;


public class MqttServer {

	/**
	 * @param port 端口
	 * @throws Exception 系统异常
	 */
	private void bind(int port) throws Exception {
		// 配置服务端的NIO线程组
		//bossGroup 用于处理接受来自客户端的连接
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		//workerGroup 用于处理接受客户端的读取信息
		EventLoopGroup workGroup = new NioEventLoopGroup();

		//JVM销毁前执行
		Runtime.getRuntime().addShutdownHook(new Thread(){
			public void run(){
				bossGroup.shutdownGracefully();
				workGroup.shutdownGracefully();
			}
		});
		
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workGroup).channel(NioServerSocketChannel.class);
			b.childHandler(new MqttServerInitializer());
			b.option(ChannelOption.SO_BACKLOG,500).childOption(ChannelOption.SO_KEEPALIVE,true);
			
			System.out.println("服务端开启等待客户端连接 ... ...");
			// 绑定端口，同步等待成功
			ChannelFuture f = b.bind(port).sync();
			// 等待服务端监听端口关闭
			f.channel().closeFuture().sync();
		} finally {
			// 风骚退出，释放NIO线程组
			bossGroup.shutdownGracefully();
			workGroup.shutdownGracefully();
		}
	}

	/**
	 * win系统入口
	 * @param args args
	 * @throws Exception 系统异常
	 */
	public static void main(String[] args) throws Exception {
		new MqttServer().bind(9211);
	}
}
